import { computed, defineComponent, PropType, reactive, Ref, ref, toRaw, watch } from 'vue'
import dayjs, { Dayjs } from 'dayjs'
import {
  Form,
  FormItem,
  Input,
  SelectOptGroup,
  Select,
  SelectOption,
  RangePicker,
  Popconfirm,
  Button,
  message,
  TableColumn,
  Modal,
} from 'ant-design-vue'
import {
  EUploadStatus,
  MediaId,
  MediaInfo,
  MediaRemoveReqParam,
  MediaSearchReqParam,
  MediauUpdateTitleReqParam,
  ResPageList,
} from '@/core/mediaRecorder/apiType'
import { copyText, downloadQrcodeFromUrl } from '@/utils/domTool'
import { deleteMedia, synthesisRetryMedia, updateInfo } from '@/api/record'

const showVideo = (url: string) => {
  //todo video show
  Modal.info({
    title: '视频播放',
    closable: true,
    icon: () => <span></span>,
    wrapClassName: 'media-record-toolPage-modal',
    width: '57.1rem',
    content: () => (
      <div
        class={
          'w-full h-full pb-3 pt-3 border-b border-t border-gray-EEEEEF border-solid text-center'
        }
      >
        <video
          class={'w-full h-full  rounded video-js'}
          ref={(r) => {
            if (r) window.videojs(r)
          }}
          style={{ height: '428px' }}
          controls
        >
          <source src={url} type="video/mp4"></source>
          <p class="vjs-no-js">您的浏览器不支持 video 标签。</p>
        </video>
      </div>
    ),
  })
}
const deleteVideo = async (param: MediaRemoveReqParam) => {
  const res = await deleteMedia(param)
  if (res.code === 0) {
    message.success('删除成功')
  } else {
    message.success('删除失败')
  }
}

const synthesisRetryVideo = async (param: Pick<MediaInfo, 'mediaId' | 'ctimeFormat'>) => {
  const res = await synthesisRetryMedia(param)
  if (res.code === 0) {
    message.success('重试成功')
  } else {
    message.success('重试失败')
  }
}
const updateTitle = async (mediaId: MediaId, title: string, reload: () => {}) => {
  const formRef: Ref<any> = ref(null)
  /**验证提交名字 */
  const formModel = reactive({ videoName: title })
  Modal.info({
    title: '修改视频名称',
    closable: true,
    width: '24.3rem',
    wrapClassName: 'media-record-toolPage-modal',
    icon: () => <span></span>,
    okText: () => <span>确定</span>,
    cancelText: () => <span>取消</span>,
    content: () => (
      <div class={'w-full h-full pb-3 pt-3  border-t border-gray-EEEEEF border-solid'}>
        <Form
          ref={(ref: any) => (formRef.value = ref)}
          layout="vertical"
          model={formModel}
          rules={{ videoName: [{ required: true, message: '请输入视频名称', trigger: 'blur' }] }}
        >
          <FormItem label={'视频名称'} name="videoName">
            <Input
              value={formModel.videoName}
              maxlength={10}
              onChange={(e) => {
                formModel.videoName = e.target.value!
              }}
            ></Input>
          </FormItem>
        </Form>
      </div>
    ),
    onOk: async () => {
      const validate = await formRef.value.validate()

      if (validate) {
        const res = await updateInfo({ title: formModel.videoName, mediaId: mediaId })
        if (res.code === 0) {
          message.success('视频名称修改成功')
          reload()
        } else {
          throw new Error(res.msg)
        }
      }
    },
    onCancel: () => {},
  })
}
export const getTableColoumn = (reload: () => {}) => (
  <>
    <TableColumn
      title={'视频ID'}
      dataIndex={'mediaId'}
      sorter={(a: any, b: any) => a['mediaId'] - b['mediaId']}
    ></TableColumn>
    <TableColumn title={'视频标题'} dataIndex={'title'}></TableColumn>
    <TableColumn
      title={'视频链接'}
      dataIndex={'url'}
      customRender={({ record }: { record: unknown }) => {
        const re = record as MediaInfo
        return (
          <a
            onClick={() => {
              showVideo(re.url)
            }}
          >
            {re.url ? re.url : ''}
          </a>
        )
      }}
    ></TableColumn>

    <TableColumn
      title={'视频状态'}
      dataIndex={'status'}
      sorter={(a: any, b: any) => a['status'] - b['status']}
      customRender={({ record }: { record: unknown }) => {
        const re = record as MediaInfo
        let statusShow = <span></span>
        switch ((record as MediaInfo).status) {
          case EUploadStatus.complexReusableFail:
            statusShow = (
              <>
                <span>合成失败</span>
              </>
            )
            break
          case EUploadStatus.complexFail:
            statusShow = <span>合成失败</span>
            break
          case EUploadStatus.complexed:
            statusShow = <span>合成完成</span>
            break
          case EUploadStatus.complexing:
            statusShow = <span>正在合成</span>
            break
        }
        return statusShow
      }}
    ></TableColumn>
    <TableColumn
      title={'创建时间'}
      sorter={(a: any, b: any) =>
        dayjs(a['ctimeFormat'] as string, 'YYYY-MM-DD HH:mm:ss').valueOf() -
        dayjs(b['ctimeFormat'] as string, 'YYYY-MM-DD HH:mm:ss').valueOf()
      }
      dataIndex={'ctimeFormat'}
    ></TableColumn>
    <TableColumn
      title={'操作'}
      align={'right'}
      dataIndex={'opGroup'}
      customRender={({ record }: { record: unknown }) => {
        const re = record as MediaInfo
        return (
          <>
            <Button
              type={'link'}
              style={{ padding: '0.25rem' }}
              onClick={() => {
                updateTitle(re.mediaId, re.title, reload)
              }}
            >
              修改标题
            </Button>
            {re.status !== EUploadStatus.complexFail && re.status !== EUploadStatus.complexing ? (
              <>
                {' '}
                <Button
                  type={'link'}
                  style={{ padding: '0.25rem' }}
                  onClick={() => {
                    copyText(re.url)
                    message.success('复制短链接成功')
                  }}
                >
                  复制短链接
                </Button>
                <Button
                  style={{ padding: '0.25rem' }}
                  type={'link'}
                  onClick={() => {
                    downloadQrcodeFromUrl(re.url, re.title + re.ctimeFormat)
                  }}
                >
                  生成二维码
                </Button>
                {/* 组件样式存在小问题  todo */}
                <Popconfirm
                  title="确认是否删除视频，删除后无法找回，用户也无法观看?"
                  ok-text="是"
                  cancel-text="否"
                  onConfirm={async () => {
                    await deleteVideo({ mediaInfos: [{ mediaId: re.mediaId, url: re.url }] })
                    reload()
                  }}
                >
                  <Button style={{ padding: '0.25rem' }} type="link" size="small">
                    删除
                  </Button>
                </Popconfirm>
              </>
            ) : (
              <>
                <Button
                  type={'link'}
                  style={{ padding: '0.25rem' }}
                  onClick={async () => {
                    await synthesisRetryVideo({ mediaId: re.mediaId, ctimeFormat: re.ctimeFormat })
                    reload()
                  }}
                >
                  重新生成
                </Button>
              </>
            )}
          </>
        )
      }}
    ></TableColumn>
  </>
)
